using MediatR;
using Medical.Api.Read.Application.Command.DepartmentManagement.Use;
using Medical.Domain.DepartmentInfo;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using Microsoft.EntityFrameworkCore;

namespace Medical.Api.Read.Application.Handler.DepartmentManagement.Use
{
    /// <summary>
    /// 获取使用登记列表处理程序
    /// </summary>
    public class GetUseCommandHandler : IRequestHandler<GetUseCommands, ApiResult<ApiPageIng<UseTable>>>
    {
        private readonly ILogger<GetUseCommandHandler> logger;
        private readonly IBaseRepository<UseTable> useRep;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志记录器</param>
        /// <param name="useRep">使用表仓储</param>
        public GetUseCommandHandler(ILogger<GetUseCommandHandler> logger, IBaseRepository<UseTable> useRep)
        {
            this.logger = logger;
            this.useRep = useRep;
        }

        /// <summary>
        /// 处理获取使用登记列表的请求
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>使用登记列表</returns>
        public async Task<ApiResult<ApiPageIng<UseTable>>> Handle(GetUseCommands request, CancellationToken cancellationToken)
        {
            try
            {
                // 构建查询
                IQueryable<UseTable> query = useRep.GetAll().Where(u => !u.IsDeleted);

                // 应用过滤条件
                if (request.RegistrationStatue.HasValue)
                {
                    query = query.Where(u => u.RegistrationStatue == request.RegistrationStatue.Value);
                }

                // 添加登记时间的条件查询
                if (request.StartTime.HasValue)
                {
                    query = query.Where(u => u.RegistrationTime >= request.StartTime.Value);
                }

                if (request.EndTime.HasValue)
                {
                    query = query.Where(u => u.RegistrationTime <= request.EndTime.Value);
                }

                // 排序并计算总数
                var totalCount = await query.CountAsync(cancellationToken);
                
                // 排序并分页
                var items = await query
                    .OrderByDescending(u => u.CreateTime)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                logger.LogInformation("获取使用登记列表成功，总数：{Count}", totalCount);

                return new ApiResult<ApiPageIng<UseTable>>
                {
                   Code = ApiEnums.Success,
                   Data = new ApiPageIng<UseTable>
                   {
                       PageData = items,
                       TotalCount = totalCount,
                       PageIndex = request.PageIndex,
                       PageSize = request.PageSize
                   }
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取使用登记列表时发生错误");
                return new ApiResult<ApiPageIng<UseTable>>
                {
                    Code = ApiEnums.Fail,
                    Data = new ApiPageIng<UseTable>(),
                    Msg = $"获取使用登记列表失败：{ex.Message}"
                };
            }
        }
    }
} 